package com.yycx.common.utils;

import org.apache.commons.io.IOUtils;
import sun.security.provider.MD5;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 获取文件hash值
 */
public class HashUtil {
    public static String sha256(File file) {
        InputStream fis = null;
        try {
            fis = new FileInputStream(file);
            return digest(fis, "SHA-256");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String sha256(InputStream inputStream) {
        try {
            return digest(inputStream, "SHA-256");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String sha256(String s) {
        InputStream fis = new ByteArrayInputStream(s.getBytes());
        try {
            return digest(fis, "SHA-256");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String md5(String s) {
        InputStream fis = new ByteArrayInputStream(s.getBytes());
        try {
            return digest(fis, "MD5");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String digest(InputStream inputStream, String type) throws IOException {
        byte buffer[] = new byte[1024 * 10];
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(type);
            for (int numRead = 0; (numRead = inputStream.read(buffer)) > 0; ) {
                messageDigest.update(buffer, 0, numRead);
            }
            byte[] digest = messageDigest.digest();
            return toHexString(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
        return null;
    }

    private static String toHexString(byte[] digest) {
        StringBuffer strHexString = new StringBuffer();
        for (int i = 0; i < digest.length; i++) {
            String hex = Integer.toHexString(0xff & digest[i]);
            if (hex.length() == 1) {
                strHexString.append('0');
            }
            strHexString.append(hex);
        }
        return strHexString.toString();
    }

    public static void main(String[] args) {
        System.out.println(sha256("Another-Redis-Desktop-Manager.1.3.9.exe"));
    }
}
